import { _decorator, Color, Component, Font, Graphics, instantiate, Label, Node, UITransform } from 'cc';
import { KuGoConfig } from '../../KugoConfig';
const { ccclass, property } = _decorator;

/**画棋盘 */
@ccclass('ChessBaseLines')
export class ChessBaseLines extends Component {
    @property(Graphics)
    graphics: Graphics = null;

    @property
    lineWidth: number = 2;

    @property(Label)
    labPoint: Label = null;
    private _gridSize: number = KuGoConfig.GridSize - 1; 
    private _lineColor = Color.BLACK
    start() {
        this.labPoint.node.active = false
        this.drawBoard();
    }

    drawBoard() {
        const g = this.graphics;
        if (!g) {
            console.error("Graphics component not found!");
            return;
        }

        g.clear();
        g.strokeColor = this._lineColor;
        g.lineWidth = this.lineWidth;

        const size = this.node.getComponent(UITransform).contentSize;
        const cellWidth = size.width / this._gridSize;
        const cellHeight = size.height / this._gridSize;

        // Draw vertical lines
        for (let i = 0; i <= this._gridSize; i++) {
            g.moveTo(i * cellWidth, 0);
            g.lineTo(i * cellWidth, size.height);
        }

        // Draw horizontal lines
        for (let i = 0; i <= this._gridSize; i++) {
            g.moveTo(0, i * cellHeight);
            g.lineTo(size.width, i * cellHeight);
        }

        g.stroke();

        // Draw diagonal line in the center cell
        const centerX = Math.floor(this._gridSize / 2);
        const centerY = Math.floor(this._gridSize / 2);
        g.moveTo(centerX * cellWidth, centerY * cellHeight);
        g.lineTo((centerX + 1) * cellWidth, (centerY + 1) * cellHeight);
        g.stroke();

       

        // Draw numbers on the left
        for (let i = 0; i <= this._gridSize; i++) {
            let lab = instantiate(this.labPoint.node)
            this.node.addChild(lab)
            lab.active = true
            lab.getComponent(Label).string = (i+1).toString()
            lab.setPosition(-50,i*cellHeight)

            lab = instantiate(this.labPoint.node)
            this.node.addChild(lab)
            lab.active = true
            lab.getComponent(Label).string = (i+1).toString()
            lab.setPosition(size.width + 50,i*cellHeight)
        }

        // Draw letters on the top
        const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        for (let i = 0; i <= this._gridSize; i++) {
            let lab = instantiate(this.labPoint.node)
            this.node.addChild(lab)
            lab.active = true
            lab.getComponent(Label).string = letters[i]
            lab.setPosition(i*cellWidth, size.height + 50)

            lab = instantiate(this.labPoint.node)
            this.node.addChild(lab)
            lab.active = true
            lab.getComponent(Label).string = letters[i]
            lab.setPosition(i*cellWidth, - 50)
        }
    }
}